use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
use dotenv::dotenv;
use log::info;

use crate::{api::success,api::error};

mod api;
mod config;
mod db;
mod log_config;

#[get("/")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
    HttpResponse::Ok().body(req_body)
}

async fn manual_hello() -> impl Responder {
    HttpResponse::Ok().body("Hey there!")
}


#[actix_web::main]
async fn main() -> std::io::Result<()> {

    dotenv().ok();
    log_config::init_log();

    let database_url = config::SERVER_CONFIG.database_url();
    let (host, port) = config::SERVER_CONFIG.get_app_host_port();
    info!("启动服务地址 http://{}:{}", host,port);

    db::init_db(database_url).await;

    HttpServer::new(|| {
        App::new()
            .service(hello)
            .service(echo)
            .service(
                web::scope("/api") // scope 相当于请求路径的前缀
                    .route("/hey", web::get().to(manual_hello)),
            )
            .route("/hey", web::get().to(manual_hello))
            .service(api::user::routes())
    })
        .bind(("127.0.0.1", 8099))?
        .run()
        .await
}